<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\StoreUser;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserController extends BaseController
{
    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function index(Request $request)
    {
        $orderBy = $request->order_by ? $request->order_by : $this->orderBy;
        $orderType = $request->order_type ? $request->order_type : $this->orderType;
        $pageSize = $request->page_size ? $request->page_size : $this->pageSize;
        $lists = User::orderBy($orderBy, $orderType);
        if ($request->get('account')) {
            $lists->where('account', 'like', '%'.$request->get('account').'%');
        }
        if ($request->get('role')) {
            $role = $request->get('role');
            $lists->whereHas('roles', function ($query) use ($role) {
                return $query->where('name', $role);
            });
        }
        // 针对老师查询时
        if ($category = $request->get('category_id')) {
            $lists->whereHas('courses', function ($query) use ($category) {
                return $query->where('category_id', $category);
            });
        }

        if ($request->get('platform') == 'backend') {
            $user = Auth::user();
            if ($user->hasRole('Teacher') && !$user->hasRole('Admin') && !$user->hasRole('Developer')) {
                $lists->where("id", Auth::id());
            }
        }
        return $lists->with(['roles'])->paginate($pageSize);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * @param StoreUser $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function store(StoreUser $request)
    {
        $password = $request->password ? bcrypt($request->password) : bcrypt('yuethink');
        $avatar = 'images/avatars/Fruit-'.rand(1, 20).'.png';
        $data = $request->only(['account', 'name']);
        $data['avatar'] = $avatar;
        $data['password'] = $password;
        if ($user = User::create($data)) {
            if ($request->roles_id) {
                $user->syncRoles($request->roles_id);
            }
            return response(['message' => '创建成功']);
        }
        return response(['message' => '创建失败'], 400);
    }

    /**
     * @param User $user
     * @return User
     */
    public function show(User $user)
    {
        $user->courses;
        return $user;
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\User  $user
     * @return \Illuminate\Http\Response
     */
    public function edit(User $user)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\User  $user
     * @return \Illuminate\Http\Response
     */
    public function update(StoreUser $request, User $user)
    {
        $data = $request->only(['avatar', 'account', 'name', 'bonus_ratio', 'details', 'parent_id', 'level_id', 'zhuangbi', 'qingbi']);
        if ($request->password) {
            $data['password'] = bcrypt($request->password);
        }
        if ($user->update($data)) {
            $user->syncRoles($request->roles_id);
            return response(['message' => '修改成功']);
        }
        return response(['message' => '修改失败'], 400);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\User  $user
     * @return \Illuminate\Http\Response
     */
    public function destroy(User $user)
    {
        if ($user->hasRole(['Admin', 'Developer'])) {
            return response(['message' => '该账号不能被删除'], 400);
        }
        $user->delete();
        return response(['message' => '删除成功']);
    }

    public function setRoles(Request $request, User $user)
    {
        $user->syncRoles($request->roles);
        return response(['message' => '设置成功']);
    }

    public function updateProfile(Request $request)
    {
        $data = $request->only(['name', 'details']);
        if ($request->password) {
            if ($request->password != $request->rePassword) {
                return response(['message' => '两次密码输入不一致'], 400);
            }
            $data['password'] = bcrypt($request->password);
        }
        if (Auth::user()->update($data)) {
            return response(['message' => '修改成功']);
        }
        return response(['message' => '修改失败'], 400);
    }

    public function distribution(Request $request)
    {
        $level = $request->level;
        // 一级分销团队
        if ($level == 1) {
            return User::where('parent_id', Auth::id())->latest()->limit(30)->get();
        }
        if ($level == 2) {
            $ids = User::where('parent_id', Auth::id())->pluck('id');
            if (count($ids) == 0) {
                return [];
            }
            return User::whereIn('parent_id', $ids)->latest()->limit(30)->get();
        }
        return [];
    }
    public function groupCount()
    {
        // 一级分销团队
        $count1 = User::where('parent_id', Auth::id())->count();
        $ids = User::where('parent_id', Auth::id())->pluck('id');
        $count2 = User::whereIn('parent_id', $ids)->count();
        return [
            'level_1' => $count1,
            'level_2' => $count2
        ];
    }
}
